<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="websocket-reloader">

  <script>

    Polymer({

      is: 'websocket-reloader',

      properties: {
        connectedOnce: false,
      },

      ready: function() {
        let isLocal = ['localhost', '127.0.0.1'].indexOf(location.hostname);
        let isHTTPS = location.protocol === 'https:';
        if (isLocal && !isHTTPS) {
          this._reconnect();
        }
      },

      // connect websocket and different handlers
      _reconnect: function() {
        let websocket = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/reload');
        websocket.onopen = this._connected.bind(this);
        websocket.onclose = this._disconnected.bind(this);
        websocket.onmessage = this._onmessage.bind(this);
      },

      _onmessage: function(e) {
        if (location.pathname.endsWith('/' + e.data)) {
          location.reload();
        }
      },

      _connected: function(e) {
        this.connectedOnce = true;
      },

      _disconnected: function(e) {
        if (!this.connectedOnce) {
          return;
        }
        // The reload endpoint has been disconnected, we are retrying in 2 seconds.
        console.log('Refresh socket disconnected');
        setTimeout(() => this._reconnect(), 2000);
      },
    });

  </script>

</dom-module>
